<template>
  <view class="knowledge-form">
    <u-form :model="formData" ref="uForm" :rules="rules">
      <u-form-item label="标题" prop="Title" :required="true">
        <u-input
          v-model="formData.Title"
          placeholder="请输入标题(不超过200字)"
          maxlength="200"
        />
      </u-form-item>

      <u-form-item
        label="分类"
        prop="CategoryName"
        :required="true"
        @click="showCategory = true"
      >
        <picker
          :show="showCategory"
          :range="categoryOptions"
          range-key="label"
          header-text="请选择分类"
          @change="handleSelectCategory"
        >
          <u-input
            v-model="formData.CategoryName"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择分类"
          ></u-input>
        </picker>
      </u-form-item>

      <u-form-item
        label="封面图片（小于1M）"
        prop="CoverImage"
        label-position="top"
        label-width="200"
      >
        <view class="mt-10px">
          <u-upload
            width="200"
            height="200"
            multipl
            :file-list="formData.CoverImage"
            :max-count="1"
            @afterRead="afterRead($event)"
            @delete="deletePic($event)"
          ></u-upload>
        </view>
      </u-form-item>

      <u-form-item
        label="内容"
        prop="Content"
        :required="true"
        label-position="top"
      >
        <textarea
          v-model="formData.Content"
          :maxlength="-1"
          class="mt-10px p-0"
          type="textarea"
          placeholder="请输入详细内容"
          border="surround"
        ></textarea>
      </u-form-item>

      <view class="bottom-box">
        <u-button
          text="提交"
          color="#386ee8"
          :throttle-time="600"
          :loading="btnLoading"
          @click="handleSubmit"
        />
      </view>
    </u-form>
  </view>
</template>

<script lang="ts">
import { showToast } from '@/utils'
import { Vue, Component } from 'vue-property-decorator'
import { submitKnowledgeApi } from './service'
import { userStore } from '@/store/modules/user'

@Component
export default class KnowledgeForm extends Vue {
  uForm: any = null
  showCategory = false
  btnLoading = false
  //用户信息
  get userInfo(): any {
    return userStore.userInfo ?? {}
  }

  formData: any = {
    Title: '',
    Content: '',
    Category: '',
    CategoryName: '',
    CoverImage: [],
    AuthorID: this.userInfo.OfficerID
  }

  fileList: Array<{ url: string }> = []

  categoryOptions = [
    { value: 1, label: '人脸识别' },
    { value: 2, label: '安全认证' },
    { value: 3, label: '数据加密' },
    { value: 4, label: '网络防护' }
  ]

  rules = {
    Title: [
      { required: true, message: '请输入标题', trigger: 'blur' },
      { max: 200, message: '标题长度不能超过200个字符', trigger: 'blur' }
    ],
    CategoryName: [
      { required: true, message: '请选择分类', trigger: 'change' }
    ],
    Content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
  }

  // 提交表单
  async handleSubmit() {
    try {
      await (this.$refs.uForm as any).validate()
      this.btnLoading = true

      const submitData = {
        ...this.formData,
        CoverImage: this.formData.CoverImage[0]?.url
          ? 'https://api.gamestrial.com/xcx_file/' +
            this.formData.CoverImage[0]?.url
          : ''
      }

      const res = await submitKnowledgeApi(submitData)
      showToast({ title: '提交成功' })
      uni.navigateBack()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      this.btnLoading = false
    }
  }
  handleSelectCategory({ detail: { value } }: any) {
    this.formData.Category = this.categoryOptions[value].value
    this.formData.CategoryName = this.categoryOptions[value].label
    this.showCategory = false
  }

  async afterRead(event: any) {
    let lists: any = [].concat(event.file)
    lists.forEach((item: any) => {
      const items = {
        ...item,
        status: 'uploading',
        message: '上传中'
      }
      this.formData.CoverImage.push(items)
    })
    const arr = this.formData.CoverImage
    for (let i = 0; i < arr.length; i++) {
      if (arr[i]?.status === 'uploading') {
        await wx.uploadFile({
          url: 'https://api.gamestrial.com/upload/upload',
          filePath: arr[i].thumb,
          name: 'file',
          formData: {
            filename: arr[i].name
          },
          success: (uploadRes) => {
            console.log(' uploadRes', uploadRes)
            let item = arr[i]
            this.formData.CoverImage.splice(
              i,
              1,
              Object.assign(item, {
                status: 'success',
                message: '',
                url: JSON.parse(uploadRes.data)?.file?.filename
              })
            )
          }
        })
      }
    }
  }
  deletePic(event: any) {
    this.formData.CoverImage.splice(event.index, 1)
  }
}
</script>

<style lang="scss" scoped>
.knowledge-form {
  padding: 20rpx;
  background-color: #ffffff;

  .u-button {
    margin-top: 30px;
  }
}
</style>
